package com.wangshuo.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.wangshuo.common.JwtHelper;
import com.wangshuo.config.Result;
import com.wangshuo.entity.Rate;
import com.wangshuo.service.RateService;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/rate")
public class RateController {
    @Resource
    private JwtHelper jwtHelper;
    @Resource
    private RateService rateService;
@GetMapping("/get")
public Result get(@RequestParam Integer gid,HttpServletRequest httpServletRequest){
    Long uid = jwtHelper.getUserId(httpServletRequest.getHeader("token"));
    LambdaQueryWrapper<Rate> lambdaQueryWrapper = new LambdaQueryWrapper<>();
    lambdaQueryWrapper.eq(Rate::getUserrid, uid);
    lambdaQueryWrapper.eq(Rate::getGoodid, gid);
    Rate rate1 = rateService.getOne(lambdaQueryWrapper);
return Result.ok(rate1);

}
    @RequestMapping("/save")
    public Result save(@RequestBody Rate rate, HttpServletRequest httpServletRequest) {
        Long uid = jwtHelper.getUserId(httpServletRequest.getHeader("token"));
        LambdaQueryWrapper<Rate> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(Rate::getUserrid, uid);
        lambdaQueryWrapper.eq(Rate::getGoodid, rate.getGoodid());
        Long count = rateService.count(lambdaQueryWrapper);
        if (count > 0) {
            Rate rate1 = rateService.getOne(lambdaQueryWrapper);
            rate1.setRate(rate.getRate());
            rateService.updateById(rate1);
        } else {
            rate.setUserrid(Math.toIntExact(uid));
            rateService.save(rate);

        }
        return Result.ok("成功");
    }
}
